package com.ruoyi.drone.controller;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import com.google.code.kaptcha.Producer;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.exception.user.CaptchaException;
import com.ruoyi.common.exception.user.CaptchaExpireException;
import com.ruoyi.common.utils.CacheUtils;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.sign.Base64;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.system.service.ISysConfigService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.drone.domain.DroneUserProfile;
import com.ruoyi.drone.domain.dto.DroneRegisterDTO;
import com.ruoyi.drone.domain.dto.DroneOrganizationRegisterDTO;
import com.ruoyi.drone.domain.dto.DroneLoginDTO;
import com.ruoyi.drone.service.IDroneRegisterService;
import com.ruoyi.drone.service.IDroneUserProfileService;
import com.ruoyi.drone.service.IDroneLoginService;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.entity.SysRole;

import javax.imageio.ImageIO;

/**
 * 无人机系统注册Controller
 *
 * @author ruoyi
 * @date 2024-01-01
 */
@RestController
@RequestMapping("/drone/register")
public class DroneRegisterController extends BaseController
{
    @Autowired
    private IDroneRegisterService registerService;

    @Autowired
    private IDroneUserProfileService userProfileService;

    @Autowired
    private IDroneLoginService loginService;

    @Autowired
    private com.ruoyi.drone.utils.JwtUtils jwtUtils;

    @Autowired
    private ISysConfigService configService;

    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;
    /**
     * 生成验证码
     */
    @GetMapping("/captcha")
    public AjaxResult getCode(HttpServletResponse response) throws IOException {
        AjaxResult ajax = AjaxResult.success();
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        ajax.put("captchaEnabled", captchaEnabled);
        if (!captchaEnabled) {
            return ajax;
        }
        // 保存验证码信息
        String uuid = IdUtils.simpleUUID(), capStr = null, code = null;
        BufferedImage image = null;
        // 生成验证码
        String captchaType = RuoYiConfig.getCaptchaType();
        if ("math".equals(captchaType)) {
            String capText = captchaProducerMath.createText();
            capStr = capText.substring(0, capText.lastIndexOf("@"));
            code = capText.substring(capText.lastIndexOf("@") + 1);
            image = captchaProducerMath.createImage(capStr);
        } else if ("char".equals(captchaType)) {
            capStr = code = captchaProducer.createText();
            image = captchaProducer.createImage(capStr);
        }
        CacheUtils.put(CacheConstants.CAPTCHA_CODE_KEY, uuid, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", os);
        } catch (IOException e) {
            return AjaxResult.error(e.getMessage());
        }
        ajax.put("uuid", uuid);
        ajax.put("img", Base64.encode(os.toByteArray()));
        return ajax;
    }
    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid)
    {
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        if (captchaEnabled)
        {
            String captcha = CacheUtils.get(CacheConstants.CAPTCHA_CODE_KEY, StringUtils.nvl(uuid, ""), String.class);
            CacheUtils.removeIfPresent(CacheConstants.CAPTCHA_CODE_KEY, StringUtils.nvl(uuid, ""));
            if (captcha == null)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
                throw new CaptchaExpireException();
            }
            if (!code.equalsIgnoreCase(captcha))
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
                throw new CaptchaException();
            }
        }
    }

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public AjaxResult login(@Valid @RequestBody DroneLoginDTO loginDTO)
    {
        try {
            String token = loginService.login(loginDTO);
            System.out.println("token = " + token);

            // 从token中解析用户信息
            Long userId = jwtUtils.getUserIdFromToken(token);
            String phone = jwtUtils.getPhoneFromToken(token);

            // 构建返回的用户信息
            Map<String, Object> userInfo = new HashMap<>();
            userInfo.put("token", token);
            userInfo.put("userId", userId);
            userInfo.put("phone", phone);

            return AjaxResult.success("登录成功", userInfo);
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }



    /**
     * 验证token
     */
    @GetMapping("/validateToken")
    public AjaxResult validateToken(@RequestHeader("Authorization") String authHeader)
    {
        try {
            String token = loginService.getTokenFromHeader(authHeader);
            if (token == null) {
                return error("Token格式错误");
            }
            
            boolean valid = loginService.validateToken(token);
            if (valid) {
                Long userId = loginService.getUserIdFromToken(token);
                String phone = loginService.getPhoneFromToken(token);
                
                java.util.Map<String, Object> userInfo = new java.util.HashMap<>();
                userInfo.put("userId", userId);
                userInfo.put("phone", phone);
                
                return AjaxResult.success("Token有效", userInfo);
            } else {
                return error("Token无效或已过期");
            }
        } catch (Exception e) {
            return error("Token验证失败：" + e.getMessage());
        }
    }

    /**
     * 飞手注册
     */
    @PostMapping("/pilot")
    public AjaxResult registerPilot(@Valid @RequestBody DroneRegisterDTO registerDTO)
    {
        try {
            boolean result = registerService.registerPilot(registerDTO);
            if (result) {
                return success("飞手注册成功，请等待审核");
            } else {
                return error("飞手注册失败");
            }
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }

    /**
     * 组织注册
     */
    @PostMapping("/organization")
    public AjaxResult registerOrganization(@Valid @RequestBody DroneOrganizationRegisterDTO orgRegisterDTO)
    {
        try {
            boolean result = registerService.registerOrganization(orgRegisterDTO);
            if (result) {
                return success("组织注册成功，请等待审核");
            } else {
                return error("组织注册失败");
            }
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }

    /**
     * 检查用户名是否唯一
     */
    @GetMapping("/checkUserName/{userName}")
    public AjaxResult checkUserName(@PathVariable String userName)
    {
        boolean unique = registerService.checkUserNameUnique(userName);
        return success(unique);
    }

    /**
     * 检查手机号是否唯一
     */
    @GetMapping("/checkPhone/{phone}")
    public AjaxResult checkPhone(@PathVariable String phone)
    {
        boolean unique = registerService.checkPhoneUnique(phone);
        return success(unique);
    }

    /**
     * 检查邮箱是否唯一
     */
    @GetMapping("/checkEmail/{email}")
    public AjaxResult checkEmail(@PathVariable String email)
    {
        boolean unique = registerService.checkEmailUnique(email);
        return success(unique);
    }

    /**
     * 检查组织名称是否唯一
     */
    @GetMapping("/checkOrgName/{orgName}")
    public AjaxResult checkOrgName(@PathVariable String orgName)
    {
        boolean unique = registerService.checkOrgNameUnique(orgName);
        return success(unique);
    }



    /**
     * 检查身份证正面照片是否有效
     */
    @GetMapping("/checkIdCardFront/{idCardFront}")
    public AjaxResult checkIdCardFront(@PathVariable String idCardFront)
    {
        // 这里可以添加照片格式验证逻辑
        return success(true);
    }

    /**
     * 检查身份证反面照片是否有效
     */
    @GetMapping("/checkIdCardBack/{idCardBack}")
    public AjaxResult checkIdCardBack(@PathVariable String idCardBack)
    {
        // 这里可以添加照片格式验证逻辑
        return success(true);
    }

    /**
     * 检查年龄是否有效
     */
    @GetMapping("/checkAge/{age}")
    public AjaxResult checkAge(@PathVariable String age)
    {
        try {
            int value = Integer.parseInt(age);
            // 基础范围校验：16-80岁
            boolean valid = value >= 16 && value <= 80;
            return success(valid);
        } catch (NumberFormatException e) {
            return success(false);
        }
    }

    /**
     * 检查飞行年限是否有效
     */
    @GetMapping("/checkFlightYears/{flightYears}")
    public AjaxResult checkFlightYears(@PathVariable String flightYears)
    {
        try {
            int value = Integer.parseInt(flightYears);
            // 基础范围校验：0-60年
            boolean valid = value >= 0 && value <= 60;
            return success(valid);
        } catch (NumberFormatException e) {
            return success(false);
        }
    }

    /**
     * 检查探险信息照片是否有效
     */
    @GetMapping("/checkExplorationInfo/{explorationInfo}")
    public AjaxResult checkExplorationInfo(@PathVariable String explorationInfo)
    {
        // 这里可以添加照片格式验证逻辑
        return success(true);
    }

    /**
     * 检查个人资质照片是否有效
     */
    @GetMapping("/checkQualification/{qualification}")
    public AjaxResult checkQualification(@PathVariable String qualification)
    {
        // 这里可以添加照片格式验证逻辑
        return success(true);
    }

    /**
     * 查询用户档案列表
     */
    @PreAuthorize("@ss.hasPermi('drone:user:list')")
    @GetMapping("/profile/list")
    public TableDataInfo list(DroneUserProfile droneUserProfile)
    {
        startPage();
        List<DroneUserProfile> list = userProfileService.selectDroneUserProfileList(droneUserProfile);
        return getDataTable(list);
    }

    /**
     * 导出用户档案列表
     */
    @PreAuthorize("@ss.hasPermi('drone:user:export')")
    @Log(title = "用户档案", businessType = BusinessType.EXPORT)
    @PostMapping("/profile/export")
    public void export(HttpServletResponse response, DroneUserProfile droneUserProfile)
    {
        List<DroneUserProfile> list = userProfileService.selectDroneUserProfileList(droneUserProfile);
        ExcelUtil<DroneUserProfile> util = new ExcelUtil<DroneUserProfile>(DroneUserProfile.class);
        util.exportExcel(response, list, "用户档案数据");
    }

    /**
     * 获取用户档案详细信息
     */
    @PreAuthorize("@ss.hasPermi('drone:user:query')")
    @GetMapping(value = "/profile/{profileId}")
    public AjaxResult getInfo(@PathVariable("profileId") Long profileId)
    {
        return success(userProfileService.selectDroneUserProfileByProfileId(profileId));
    }

    /**
     * 新增用户档案
     */
    @PreAuthorize("@ss.hasPermi('drone:user:add')")
    @Log(title = "用户档案", businessType = BusinessType.INSERT)
    @PostMapping("/profile")
    public AjaxResult add(@RequestBody DroneUserProfile droneUserProfile)
    {
        return toAjax(userProfileService.insertDroneUserProfile(droneUserProfile));
    }

    /**
     * 修改用户档案
     */
    @PreAuthorize("@ss.hasPermi('drone:user:edit')")
    @Log(title = "用户档案", businessType = BusinessType.UPDATE)
    @PutMapping("/profile")
    public AjaxResult edit(@RequestBody DroneUserProfile droneUserProfile)
    {
        return toAjax(userProfileService.updateDroneUserProfile(droneUserProfile));
    }

    /**
     * 删除用户档案
     */
    @PreAuthorize("@ss.hasPermi('drone:user:remove')")
    @Log(title = "用户档案", businessType = BusinessType.DELETE)
	@DeleteMapping("/profile/{profileIds}")
    public AjaxResult remove(@PathVariable Long[] profileIds)
    {
        return toAjax(userProfileService.deleteDroneUserProfileByProfileIds(profileIds));
    }
}
